package com.example.litterpainterdemo.draw.view

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.litterpainterdemo.data.PictureViewModel
import com.example.litterpainterdemo.databinding.FragmentDrawBinding
import com.example.litterpainterdemo.db.Picture
import com.example.litterpainterdemo.draw.color.ColorAdapter
import com.example.litterpainterdemo.utils.BitmapUtils
import com.example.litterpainterdemo.utils.ColorUtil
import com.example.litterpainterdemo.utils.FileUtils
import com.example.litterpainterdemo.utils.TimeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class DrawFragment : Fragment() {
    private lateinit var binding:FragmentDrawBinding
    private val mViewModel: DrawViewModel by viewModels() //创建自己的viewmodel
    private val mAdapter = ColorAdapter()
    private val args: DrawFragmentArgs by navArgs()
    private val pictureViewModel:PictureViewModel by activityViewModels()


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentDrawBinding.inflate(inflater,container,false)
        return  binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //配置viewModel
        binding.toolContainer.viewMOdel = mViewModel
        binding.drawView.viewModel = mViewModel
        binding.drawView.lifecycleOwner = viewLifecycleOwner
        mAdapter.viewModel = mViewModel
        binding.progressView.viewModel = mViewModel

        if(args.currentPicture != null){
            lifecycleScope.launch {
                binding.drawView.mBitmap = BitmapUtils.loadOriginalDrawing(args.currentPicture!!.url)
                binding.editText.setText(args.currentPicture!!.name)
            }
        }


        val colors = ColorUtil.getColors(100)
        //配置RecycleView
        binding.recycleView.apply {
            layoutManager = LinearLayoutManager(context,RecyclerView.HORIZONTAL,false)
            adapter = mAdapter
        }

        mViewModel.colorModels.observe(viewLifecycleOwner){
            mAdapter.setData(it)
        }


        binding.backBtn.setOnClickListener {


            if(args.currentPicture == null && !binding.drawView.isEmpty()) {
                //显示
                show()
                lifecycleScope.launch {
                    //获取bitmap
                    val bitmap = BitmapUtils.convertViewToBitmap(binding.drawView)
                    //获取时间
                    val time = TimeUtils.time()
                    //获取名字
                    val name = binding.editText.text.trim().toString()
                    //获取url
                    val url = FileUtils.saveBitmap(bitmap)
                    //获取缩略图
                    val thumbnail = BitmapUtils.convertThumbnail(bitmap,0.5f)
                    //写入数据到数据库
                    Log.v("wjb","新增一副画，保存之前：${pictureViewModel.pictures.value!!.size}")
                    pictureViewModel.insertData(
                        Picture(0,name,time,url,thumbnail)
                    )
                    delay(1000)
                    hide()
                    Log.v("wjb","新增一副画，保存之后： ${pictureViewModel.pictures.value!!.size}")
                    findNavController().navigateUp()
                }
            }

            args.currentPicture?.let {
                lifecycleScope.launch(Dispatchers.IO) {
                    withContext(Dispatchers.Main){
                        //显示加载视图
                        show()
                    }
                //记录是否需要更新
                var update: Boolean = false

                if (!binding.drawView.isEmpty()) {//画图 需要更新
                        //获取bitmap
                        val bitmap = BitmapUtils.convertViewToBitmap(binding.drawView)
                        //获取时间
                        val time = TimeUtils.time()
                        //获取url
                        val mUrl = FileUtils.saveBitmap(bitmap)
                        //删除之前的文件
                        FileUtils.deleteFile(it.url)
                        //保存当前的文件
                        it.url = mUrl
                        it.time = time
                        //获取缩略图
                        val thumbnail = BitmapUtils.convertThumbnail(bitmap, 0.5f)
                        it.thumbnail = thumbnail
                        update = true
                    }

                if (it.name != binding.editText.text.toString()) {//修改名称
                    it.name = binding.editText.text.trim().toString()
                    update = true
                }

                if (update) {//更新
                    Log.v("wjb","更新一幅画，更新之前：${pictureViewModel.pictures.value!!.size}")
                    pictureViewModel.updateData(it)
                }
                withContext(Dispatchers.Main) {
                    //关闭视图
                    delay(1000)
                    hide()
                    Log.v("wjb","更新一幅画，更新之后：${pictureViewModel.pictures.value!!.size}")
                    findNavController().navigateUp()
                     }
                 }
            }

            if(args.currentPicture == null && binding.drawView.isEmpty()){
                findNavController().navigateUp()
            }

        }

    }

    private fun show(){
        binding.loadView.visibility = View.VISIBLE
        binding.loadView.start()
    }


    fun hide(){
        binding.loadView.visibility = View.INVISIBLE
        binding.loadView.stop()
    }
}